package ServerConnection;

import Client.ServerInfo;
import Message.AccountAddFriendInfo;
import Message.Relationship;
import utils.AccountAddFriendInfoListOfAll;
import utils.FriendArrayList;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;


/**
 * 该类用来处理客户端发起的回应好友添加申请（同意添加或拒绝添加）的请求
 */
public class ResponseFriendRequestServer {
    public static void main(String[] args) {
        try {
            DatabaseServer databaseServer = new DatabaseServer();
            ServerSocket serverSocket = new ServerSocket(ServerInfo.SERVER_RESPONSEFRIENDREQUEST_PORT);
            System.out.println("返回添加好友申请服务成功启动！");
            Socket socket;
            while (true) {
                socket = serverSocket.accept();
                Thread handle = new Thread(new ThreadHandleResponseFriendRequest(socket, databaseServer));
                handle.start();
            }
        } catch (IOException e) {
            System.out.println("WARNING:ResponseFriendRequestServer Init fail,Reason:socket has ioException.");
        }
    }
}

/**
 * 该类是用来处理客户端发起的回应好友添加申请（同意添加或拒绝添加）的请求的线程类
 */
class ThreadHandleResponseFriendRequest implements Runnable {
    Socket socket = null;
    DatabaseServer databaseServer;

    public ThreadHandleResponseFriendRequest(Socket socket, DatabaseServer databaseServer) {
        super();
        this.socket = socket;
        this.databaseServer = databaseServer;
    }

    @Override
    public void run() {
        try {
            System.out.println("收到用户确认好友申请的请求，正在处理");
            //获取从客户端得到的消息，并且执行了消息。
            InputStream inputStream = socket.getInputStream();
            ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
            AccountAddFriendInfoListOfAll accountAddFriendInfoListOfAll = (AccountAddFriendInfoListOfAll) objectInputStream.readObject();

            String userId = accountAddFriendInfoListOfAll.get(0).get(0).getUserIdInDatabaseTo();//获取处理好友申请的用户id
            //relationshipArrayList保存已经成立的好友关系，用于插入数据库UserFriendList
            ArrayList<Relationship> relationshipArrayList = new ArrayList<Relationship>();
            for (int i = 0; i < accountAddFriendInfoListOfAll.size(); i++) {
                for (int j = 0; j < accountAddFriendInfoListOfAll.get(i).size(); j++) {
                    AccountAddFriendInfo accountAddFriendInfo = accountAddFriendInfoListOfAll.get(i).get(j);
                    int agree = accountAddFriendInfo.getAgree() ? 1 : 0; //因MySQL没有boolean字段，而是采用int类型存储agree，所以这里将Boolean转int
                    String userFrom = accountAddFriendInfo.getUserIdInDatabaseFrom();
                    String userTo = accountAddFriendInfo.getUserIdInDatabaseTo();
                    String sql = String.format("UPDATE QQ.FriendRequest SET Agree = %d " +
                                    "where `To` = %s and `From` = %s and `When` = '%s' and Info = '%s' and Response = 1;",
                            agree, userTo, userFrom, accountAddFriendInfo.getTime(), accountAddFriendInfo.getMessageInfo());
                    Boolean result = databaseServer.doExecute(sql);
                    System.out.println("result:" + result);
                    if (result && agree == 1) {
                        Relationship relationship = new Relationship(userTo, userFrom);
                        relationshipArrayList.add(relationship);
                    }
                }
            }

            String sqlToInsertRelationship = "insert into UserFriendList (Uid1,Uid2) values(?, ?)";
            Boolean res = databaseServer.bulkInsertRelationship(sqlToInsertRelationship, relationshipArrayList);
            if (res) {
                System.out.println("批量插入好友关系成功");
            } else {
                System.out.println("批量插入好友关系失败");
            }
            String sqlToGetFriendList = "SELECT * From UserFriendList WHERE Uid1=" + userId;
            FriendArrayList friendArrayList = new FriendArrayList();//该数组用来存储用户的好友列表
            ResultSet resultSet = databaseServer.returnResultSet(sqlToGetFriendList);
            while (resultSet.next()) {
                String Uid2 = resultSet.getString("Uid2");
                System.out.println("uid2: " + Uid2);
                friendArrayList.add(Uid2);
            }
            //返还执行的结果到客户端。
            OutputStream outputStream = socket.getOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
            objectOutputStream.writeObject(friendArrayList);

            inputStream.close();
            objectInputStream.close();
            outputStream.close();
            socket.close();

        } catch (IOException | ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }
}